package com.neuedu.corejava.ch12;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLBoundFault;

public class MyFileReader {
	/**
	 * 拷贝文件，并把小写l全部修改为大写L
	 * 
	 * @param src
	 * @param desc
	 */

	public void copyAndFilter(String src, String desc) {

		if (src == null || desc == null) {
			return;
		}
		File sercFile = new File(src);
		File destFile = new File(desc);

		if (!sercFile.exists()) {
			return;
		}
		FileReader reader = null;
		FileWriter writer = null;
		BufferedReader bufferedReader = null;
		try {
			if (!destFile.exists()) {
				destFile.getParentFile().mkdirs();
				destFile.createNewFile();
			}
			reader = new FileReader(sercFile);// 节点流
			bufferedReader = new BufferedReader(reader);// 处理流
			writer = new FileWriter(destFile,true);// 节点流
			String data = null;
			// 一次读取一行内容，文件读取完毕返回null
			while ((data = bufferedReader.readLine()) != null) {

				String newstr = data.replaceAll("l", "L");
				writer.write(newstr);
				writer.write("\r\n");
			}

		} catch (IOException e) {
			e.printStackTrace();

		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (bufferedReader != null) {
					try {
						bufferedReader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					if (reader != null) {
						try {
							reader.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}

		}
	}

	/**
	 * 把一段文本 内容写入到一个指定文件中
	 * 
	 * @param filename
	 * @param content
	 */
	public void writeFile(String filename, String content) {
		if (filename == null) {
			return;

		}
		File file = new File(filename);
		FileOutputStream outputStream = null;
		try {
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			// 文件的写入有两种模式，false 重写；true追加
			outputStream = new FileOutputStream(file);
			// 需要把字符转换成字节数字，转换时需要注意可能产生乱码
			outputStream.write(content.getBytes());

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void main(String[] args) {

		MyFileReader fileReader = new MyFileReader();
		fileReader.writeFile("c:\\test.txt", "holle world1");
		System.out.println("新增成功");
		
		fileReader.copyAndFilter("c:\\test.txt", "c:\\test2.txt");
		System.out.println("修改成功");
	}

}
